package com.example.demo.config;

import com.mysql.cj.jdbc.MysqlDataSource;
import org.beetl.sql.core.*;
import org.beetl.sql.core.db.DBStyle;
import org.beetl.sql.core.db.MySqlStyle;
import org.beetl.sql.ext.DebugInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;

/**
 * @author gyq
 * @description
 * @datetime 2018/1/23 21:24
 */
@Configuration
public class DataSourceConfig {

    @Bean(name = "datasource")
    public DataSource datasource(Environment env) {
        MysqlDataSource datasource = new MysqlDataSource();
        datasource.setUrl(env.getProperty("spring.datasource.url"));
        datasource.setUser(env.getProperty("spring.datasource.username"));
        datasource.setPassword(env.getProperty("spring.datasource.password"));
        datasource.setDatabaseName(env.getProperty("spring.datasource.dbName"));
        datasource.setPort(Integer.valueOf(env.getProperty("spring.datasource.port")));
        ConnectionSource source = ConnectionSourceHelper.getSingle(datasource);
        DBStyle mysql = new MySqlStyle();
        // sql语句放在classpagth的/sql 目录下
        SQLLoader loader = new ClasspathLoader("/sql");
        // 数据库命名跟java命名一样，所以采用DefaultNameConversion，还有一个是UnderlinedNameConversion，下划线风格的
        UnderlinedNameConversion nc = new UnderlinedNameConversion();
        // 最后，创建一个SQLManager,DebugInterceptor 不是必须的，但可以通过它查看sql执行情况
        SQLManager sqlManager = new SQLManager(mysql, loader, source, nc, new Interceptor[]{new DebugInterceptor()});



        //datasource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
        return datasource;
    }
}
